import { defineStore } from "pinia";
import { store } from "/@/store";
import { userType } from "./types";
// import { useRouter } from "vue-router";
import { refreshToken } from "/@/api/user";
import { storageLocal, storageSession } from "/@/utils/storage";
import { getToken, removeToken, setToken } from "/@/utils/auth";
import { useMultiTagsStoreHook } from "/@/store/modules/multiTags";
import LoginApi, {
  certLoginApi,
  getUserInfoApi
} from "/@/api/api/login/LoginApi";
import { Crypto } from "rclink/lib";
import { IResult } from "/@/common/request";
import { v4 } from "uuid";

const data = getToken();
let token = "";
let name = "";
let privateKey = "";
if (data) {
  const dataJson = JSON.parse(data);
  if (dataJson) {
    token = dataJson?.accessToken;
    name = dataJson?.name ?? "admin";
    privateKey = dataJson?.privateKey;
  }
}

const loginApi = new LoginApi();
export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    token,
    name,
    privateKey,
    cert: "",
    certName: "",
    creditCode: "",
    role: "",
    publicKey: "",
    uuid: "",
    chainCodeVersion: 1
  }),
  actions: {
    SET_UUID() {
      if (!this.uuid) {
        this.uuid = v4().split("-")[0] + new Date().getTime();
      }
    },
    SET_CHAIN_CODE_VERSION(chainCodeVersion) {
      this.chainCodeVersion = chainCodeVersion;
    },
    SET_ROLE(role) {
      this.role = role;
    },
    SET_TOKEN(token) {
      this.token = token;
    },
    SET_NAME(name) {
      this.name = name;
    },
    SET_PRIVATE_KEY(privateKey) {
      this.privateKey = privateKey;
    },
    SET_CERT(cert) {
      this.cert = cert;
      if (cert) {
        const { ImportKey, GetKeyPEM } = Crypto;
        const pubKeyObj = ImportKey(cert);
        this.publicKey = GetKeyPEM(pubKeyObj);
      } else {
        this.publicKey = "";
      }
    },
    SET_CERT_NAME(certName) {
      this.certName = certName;
    },
    SET_CREDIT_CODE(creditCode) {
      this.creditCode = creditCode;
    },
    // 登入
    async loginByUsername(data) {
      return new Promise<IResult>((resolve, reject) => {
        if (!data || !data.username || !data.password) {
          reject("请填写登录信息");
          return;
        }
        if (!data.password.startsWith("-----BEGIN PRIVATE KEY-----")) {
          reject("私钥格式不正确");
          return;
        }
        const signAlg = "SHA256withECDSA";
        const { Sign } = Crypto;
        const message = v4().split("-")[0] + new Date().getTime();
        const signature = Sign({
          prvKey: data.password,
          data: message,
          alg: signAlg,
          provider: "jsrsasign"
        }).toString("hex");

        const param = {
          username: data.username,
          signature,
          message
        };
        certLoginApi(param)
          .then(ref => {
            if (ref.code === 0) {
              const info = ref.data;
              const pureInfo = {
                name: ref.data.creditCode,
                accessToken: info.token,
                expires: info.expire,
                privateKey: data.password,
                role: ref.data.role
              };
              this.SET_ROLE(ref.data.role);
              setToken(pureInfo);
              storageSession.setItem("info", {
                username: ref.data.creditCode,
                accessToken: info.token,
                role: ref.data.role
              });
            }
            resolve(ref);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 登出 清空缓存
    async logOut() {
      console.log("LogOut");
      await loginApi.logout({ loginName: this.name });
      this.token = "";
      this.name = "";
      removeToken();
      this.SET_ROLE("");
      this.SET_CERT_NAME("");
      this.SET_CREDIT_CODE("");
      this.SET_CERT("");
      this.SET_NAME("");
      this.SET_TOKEN("");
      this.SET_PRIVATE_KEY("");
      storageLocal.clear();
      storageSession.clear();
      useMultiTagsStoreHook().handleTags("equal", [
        {
          path: "/welcome",
          parentPath: "/",
          meta: {
            title: "message.hshome",
            icon: "el-icon-s-home",
            i18n: true,
            showLink: true
          }
        }
      ]);
      window.location.reload();
      // router.push("/login");
    },
    async getUserInfo() {
      getUserInfoApi().then(res => {
        if (res.code === 0) {
          this.SET_CREDIT_CODE(res.data.CREDIT_CODE);
          this.SET_CERT(res.data.CERT);
          this.SET_CERT_NAME(res.data.CERT_NAME);
          this.SET_ROLE(res.data.SYS_ROLE);
          this.SET_CHAIN_CODE_VERSION(res.data.CHAIN_CODE_VERSION);
        }
      });
    },
    // 刷新token
    async refreshToken(data) {
      return refreshToken(data).then(data => {
        if (data) {
          setToken(data);
          return data;
        }
      });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
